Message: Throw if given invalid serialized data
[lhc/web/wiklou.git] / includes / Message.php
1 <?php
2 /**
3 * Fetching and processing of interface messages.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @author Niklas Laxström
22 */
23 use MediaWiki\MediaWikiServices;
24
25 /**
26 * The Message class provides methods which fulfil two basic services:
27 * - fetching interface messages
28 * - processing messages into a variety of formats
29 *
30 * First implemented with MediaWiki 1.17, the Message class is intended to
31 * replace the old wfMsg* functions that over time grew unusable.
32 * @see https://www.mediawiki.org/wiki/Manual:Messages_API for equivalences
33 * between old and new functions.
34 *
35 * You should use the wfMessage() global function which acts as a wrapper for
36 * the Message class. The wrapper let you pass parameters as arguments.
37 *
38 * The most basic usage cases would be:
39 *
40 * @code
41 * // Initialize a Message object using the 'some_key' message key
42 * $message = wfMessage( 'some_key' );
43 *
44 * // Using two parameters those values are strings 'value1' and 'value2':
45 * $message = wfMessage( 'some_key',
46 * 'value1', 'value2'
47 * );
48 * @endcode
49 *
50 * @section message_global_fn Global function wrapper:
51 *
52 * Since wfMessage() returns a Message instance, you can chain its call with
53 * a method. Some of them return a Message instance too so you can chain them.
54 * You will find below several examples of wfMessage() usage.
55 *
56 * Fetching a message text for interface message:
57 *
58 * @code
59 * $button = Xml::button(
60 * wfMessage( 'submit' )->text()
61 * );
62 * @endcode
63 *
64 * A Message instance can be passed parameters after it has been constructed,
65 * use the params() method to do so:
66 *
67 * @code
68 * wfMessage( 'welcome-to' )
69 * ->params( $wgSitename )
70 * ->text();
71 * @endcode
72 *
73 * {{GRAMMAR}} and friends work correctly:
74 *
75 * @code
76 * wfMessage( 'are-friends',
77 * $user, $friend
78 * );
79 * wfMessage( 'bad-message' )
80 * ->rawParams( '<script>...</script>' )
81 * ->escaped();
82 * @endcode
83 *
84 * @section message_language Changing language:
85 *
86 * Messages can be requested in a different language or in whatever current
87 * content language is being used. The methods are:
88 * - Message->inContentLanguage()
89 * - Message->inLanguage()
90 *
91 * Sometimes the message text ends up in the database, so content language is
92 * needed:
93 *
94 * @code
95 * wfMessage( 'file-log',
96 * $user, $filename
97 * )->inContentLanguage()->text();
98 * @endcode
99 *
100 * Checking whether a message exists:
101 *
102 * @code
103 * wfMessage( 'mysterious-message' )->exists()
104 * // returns a boolean whether the 'mysterious-message' key exist.
105 * @endcode
106 *
107 * If you want to use a different language:
108 *
109 * @code
110 * $userLanguage = $user->getOption( 'language' );
111 * wfMessage( 'email-header' )
112 * ->inLanguage( $userLanguage )
113 * ->plain();
114 * @endcode
115 *
116 * @note You can parse the text only in the content or interface languages
117 *
118 * @section message_compare_old Comparison with old wfMsg* functions:
119 *
120 * Use full parsing:
121 *
122 * @code
123 * // old style:
124 * wfMsgExt( 'key', [ 'parseinline' ], 'apple' );
125 * // new style:
126 * wfMessage( 'key', 'apple' )->parse();
127 * @endcode
128 *
129 * Parseinline is used because it is more useful when pre-building HTML.
130 * In normal use it is better to use OutputPage::(add|wrap)WikiMsg.
131 *
132 * Places where HTML cannot be used. {{-transformation is done.
133 * @code
134 * // old style:
135 * wfMsgExt( 'key', [ 'parsemag' ], 'apple', 'pear' );
136 * // new style:
137 * wfMessage( 'key', 'apple', 'pear' )->text();
138 * @endcode
139 *
140 * Shortcut for escaping the message too, similar to wfMsgHTML(), but
141 * parameters are not replaced after escaping by default.
142 * @code
143 * $escaped = wfMessage( 'key' )
144 * ->rawParams( 'apple' )
145 * ->escaped();
146 * @endcode
147 *
148 * @section message_appendix Appendix:
149 *
150 * @todo
151 * - test, can we have tests?
152 * - this documentation needs to be extended
153 *
154 * @see https://www.mediawiki.org/wiki/WfMessage()
155 * @see https://www.mediawiki.org/wiki/New_messages_API
156 * @see https://www.mediawiki.org/wiki/Localisation
157 *
158 * @since 1.17
159 */
160 class Message implements MessageSpecifier, Serializable {
161 /** Use message text as-is */
162 const FORMAT_PLAIN = 'plain';
163 /** Use normal wikitext -> HTML parsing (the result will be wrapped in a block-level HTML tag) */
164 const FORMAT_BLOCK_PARSE = 'block-parse';
165 /** Use normal wikitext -> HTML parsing but strip the block-level wrapper */
166 const FORMAT_PARSE = 'parse';
167 /** Transform {{..}} constructs but don't transform to HTML */
168 const FORMAT_TEXT = 'text';
169 /** Transform {{..}} constructs, HTML-escape the result */
170 const FORMAT_ESCAPED = 'escaped';
171
172 /**
173 * Mapping from Message::listParam() types to Language methods.
174 * @var array
175 */
176 protected static $listTypeMap = [
177 'comma' => 'commaList',
178 'semicolon' => 'semicolonList',
179 'pipe' => 'pipeList',
180 'text' => 'listToText',
181 ];
182
183 /**
184 * In which language to get this message. True, which is the default,
185 * means the current user language, false content language.
186 *
187 * @var bool
188 */
189 protected $interface = true;
190
191 /**
192 * In which language to get this message. Overrides the $interface setting.
193 *
194 * @var Language|bool Explicit language object, or false for user language
195 */
196 protected $language = false;
197
198 /**
199 * @var string The message key. If $keysToTry has more than one element,
200 * this may change to one of the keys to try when fetching the message text.
201 */
202 protected $key;
203
204 /**
205 * @var string[] List of keys to try when fetching the message.
206 */
207 protected $keysToTry;
208
209 /**
210 * @var array List of parameters which will be substituted into the message.
211 */
212 protected $parameters = [];
213
214 /**
215 * @var string
216 * @deprecated
217 */
218 protected $format = 'parse';
219
220 /**
221 * @var bool Whether database can be used.
222 */
223 protected $useDatabase = true;
224
225 /**
226 * @var Title Title object to use as context.
227 */
228 protected $title = null;
229
230 /**
231 * @var Content Content object representing the message.
232 */
233 protected $content = null;
234
235 /**
236 * @var string
237 */
238 protected $message;
239
240 /**
241 * @since 1.17
242 * @param string|string[]|MessageSpecifier $key Message key, or array of
243 * message keys to try and use the first non-empty message for, or a
244 * MessageSpecifier to copy from.
245 * @param array $params Message parameters.
246 * @param Language|null $language [optional] Language to use (defaults to current user language).
247 * @throws InvalidArgumentException
248 */
249 public function __construct( $key, $params = [], Language $language = null ) {
250 if ( $key instanceof MessageSpecifier ) {
251 if ( $params ) {
252 throw new InvalidArgumentException(
253 '$params must be empty if $key is a MessageSpecifier'
254 );
255 }
256 $params = $key->getParams();
257 $key = $key->getKey();
258 }
259
260 if ( !is_string( $key ) && !is_array( $key ) ) {
261 throw new InvalidArgumentException( '$key must be a string or an array' );
262 }
263
264 $this->keysToTry = (array)$key;
265
266 if ( empty( $this->keysToTry ) ) {
267 throw new InvalidArgumentException( '$key must not be an empty list' );
268 }
269
270 $this->key = reset( $this->keysToTry );
271
272 $this->parameters = array_values( $params );
273 // User language is only resolved in getLanguage(). This helps preserve the
274 // semantic intent of "user language" across serialize() and unserialize().
275 $this->language = $language ?: false;
276 }
277
278 /**
279 * @see Serializable::serialize()
280 * @since 1.26
281 * @return string
282 */
283 public function serialize() {
284 return serialize( [
285 'interface' => $this->interface,
286 'language' => $this->language ? $this->language->getCode() : false,
287 'key' => $this->key,
288 'keysToTry' => $this->keysToTry,
289 'parameters' => $this->parameters,
290 'format' => $this->format,
291 'useDatabase' => $this->useDatabase,
292 'title' => $this->title,
293 ] );
294 }
295
296 /**
297 * @see Serializable::unserialize()
298 * @since 1.26
299 * @param string $serialized
300 */
301 public function unserialize( $serialized ) {
302 $data = unserialize( $serialized );
303 if ( !is_array( $data ) ) {
304 throw new InvalidArgumentException( __METHOD__ . ': Invalid serialized data' );
305 }
306
307 $this->interface = $data['interface'];
308 $this->key = $data['key'];
309 $this->keysToTry = $data['keysToTry'];
310 $this->parameters = $data['parameters'];
311 $this->format = $data['format'];
312 $this->useDatabase = $data['useDatabase'];
313 $this->language = $data['language'] ? Language::factory( $data['language'] ) : false;
314 $this->title = $data['title'];
315 }
316
317 /**
318 * @since 1.24
319 *
320 * @return bool True if this is a multi-key message, that is, if the key provided to the
321 * constructor was a fallback list of keys to try.
322 */
323 public function isMultiKey() {
324 return count( $this->keysToTry ) > 1;
325 }
326
327 /**
328 * @since 1.24
329 *
330 * @return string[] The list of keys to try when fetching the message text,
331 * in order of preference.
332 */
333 public function getKeysToTry() {
334 return $this->keysToTry;
335 }
336
337 /**
338 * Returns the message key.
339 *
340 * If a list of multiple possible keys was supplied to the constructor, this method may
341 * return any of these keys. After the message has been fetched, this method will return
342 * the key that was actually used to fetch the message.
343 *
344 * @since 1.21
345 *
346 * @return string
347 */
348 public function getKey() {
349 return $this->key;
350 }
351
352 /**
353 * Returns the message parameters.
354 *
355 * @since 1.21
356 *
357 * @return array
358 */
359 public function getParams() {
360 return $this->parameters;
361 }
362
363 /**
364 * Returns the message format.
365 *
366 * @since 1.21
367 *
368 * @return string
369 * @deprecated since 1.29 formatting is not stateful
370 */
371 public function getFormat() {
372 wfDeprecated( __METHOD__, '1.29' );
373 return $this->format;
374 }
375
376 /**
377 * Returns the Language of the Message.
378 *
379 * @since 1.23
380 *
381 * @return Language
382 */
383 public function getLanguage() {
384 // Defaults to false which means current user language
385 return $this->language ?: RequestContext::getMain()->getLanguage();
386 }
387
388 /**
389 * Factory function that is just wrapper for the real constructor. It is
390 * intended to be used instead of the real constructor, because it allows
391 * chaining method calls, while new objects don't.
392 *
393 * @since 1.17
394 *
395 * @param string|string[]|MessageSpecifier $key
396 * @param mixed $param,... Parameters as strings.
397 *
398 * @return Message
399 */
400 public static function newFromKey( $key /*...*/ ) {
401 $params = func_get_args();
402 array_shift( $params );
403 return new self( $key, $params );
404 }
405
406 /**
407 * Transform a MessageSpecifier or a primitive value used interchangeably with
408 * specifiers (a message key string, or a key + params array) into a proper Message.
409 *
410 * Also accepts a MessageSpecifier inside an array: that's not considered a valid format
411 * but is an easy error to make due to how StatusValue stores messages internally.
412 * Further array elements are ignored in that case.
413 *
414 * @param string|array|MessageSpecifier $value
415 * @return Message
416 * @throws InvalidArgumentException
417 * @since 1.27
418 */
419 public static function newFromSpecifier( $value ) {
420 $params = [];
421 if ( is_array( $value ) ) {
422 $params = $value;
423 $value = array_shift( $params );
424 }
425
426 if ( $value instanceof Message ) { // Message, RawMessage, ApiMessage, etc
427 $message = clone $value;
428 } elseif ( $value instanceof MessageSpecifier ) {
429 $message = new Message( $value );
430 } elseif ( is_string( $value ) ) {
431 $message = new Message( $value, $params );
432 } else {
433 throw new InvalidArgumentException( __METHOD__ . ': invalid argument type '
434 . gettype( $value ) );
435 }
436
437 return $message;
438 }
439
440 /**
441 * Factory function accepting multiple message keys and returning a message instance
442 * for the first message which is non-empty. If all messages are empty then an
443 * instance of the first message key is returned.
444 *
445 * @since 1.18
446 *
447 * @param string|string[] $keys,... Message keys, or first argument as an array of all the
448 * message keys.
449 *
450 * @return Message
451 */
452 public static function newFallbackSequence( /*...*/ ) {
453 $keys = func_get_args();
454 if ( func_num_args() == 1 ) {
455 if ( is_array( $keys[0] ) ) {
456 // Allow an array to be passed as the first argument instead
457 $keys = array_values( $keys[0] );
458 } else {
459 // Optimize a single string to not need special fallback handling
460 $keys = $keys[0];
461 }
462 }
463 return new self( $keys );
464 }
465
466 /**
467 * Get a title object for a mediawiki message, where it can be found in the mediawiki namespace.
468 * The title will be for the current language, if the message key is in
469 * $wgForceUIMsgAsContentMsg it will be append with the language code (except content
470 * language), because Message::inContentLanguage will also return in user language.
471 *
472 * @see $wgForceUIMsgAsContentMsg
473 * @return Title
474 * @since 1.26
475 */
476 public function getTitle() {
477 global $wgForceUIMsgAsContentMsg;
478
479 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
480 $lang = $this->getLanguage();
481 $title = $this->key;
482 if (
483 !$lang->equals( $contLang )
484 && in_array( $this->key, (array)$wgForceUIMsgAsContentMsg )
485 ) {
486 $title .= '/' . $lang->getCode();
487 }
488
489 return Title::makeTitle(
490 NS_MEDIAWIKI, $contLang->ucfirst( strtr( $title, ' ', '_' ) ) );
491 }
492
493 /**
494 * Adds parameters to the parameter list of this message.
495 *
496 * @since 1.17
497 *
498 * @param mixed $args,... Parameters as strings or arrays from
499 * Message::numParam() and the like, or a single array of parameters.
500 *
501 * @return Message $this
502 */
503 public function params( /*...*/ ) {
504 $args = func_get_args();
505
506 // If $args has only one entry and it's an array, then it's either a
507 // non-varargs call or it happens to be a call with just a single
508 // "special" parameter. Since the "special" parameters don't have any
509 // numeric keys, we'll test that to differentiate the cases.
510 if ( count( $args ) === 1 && isset( $args[0] ) && is_array( $args[0] ) ) {
511 if ( $args[0] === [] ) {
512 $args = [];
513 } else {
514 foreach ( $args[0] as $key => $value ) {
515 if ( is_int( $key ) ) {
516 $args = $args[0];
517 break;
518 }
519 }
520 }
521 }
522
523 $this->parameters = array_merge( $this->parameters, array_values( $args ) );
524 return $this;
525 }
526
527 /**
528 * Add parameters that are substituted after parsing or escaping.
529 * In other words the parsing process cannot access the contents
530 * of this type of parameter, and you need to make sure it is
531 * sanitized beforehand. The parser will see "$n", instead.
532 *
533 * @since 1.17
534 *
535 * @param mixed $params,... Raw parameters as strings, or a single argument that is
536 * an array of raw parameters.
537 *
538 * @return Message $this
539 */
540 public function rawParams( /*...*/ ) {
541 $params = func_get_args();
542 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
543 $params = $params[0];
544 }
545 foreach ( $params as $param ) {
546 $this->parameters[] = self::rawParam( $param );
547 }
548 return $this;
549 }
550
551 /**
552 * Add parameters that are numeric and will be passed through
553 * Language::formatNum before substitution
554 *
555 * @since 1.18
556 *
557 * @param mixed $param,... Numeric parameters, or a single argument that is
558 * an array of numeric parameters.
559 *
560 * @return Message $this
561 */
562 public function numParams( /*...*/ ) {
563 $params = func_get_args();
564 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
565 $params = $params[0];
566 }
567 foreach ( $params as $param ) {
568 $this->parameters[] = self::numParam( $param );
569 }
570 return $this;
571 }
572
573 /**
574 * Add parameters that are durations of time and will be passed through
575 * Language::formatDuration before substitution
576 *
577 * @since 1.22
578 *
579 * @param int|int[] $param,... Duration parameters, or a single argument that is
580 * an array of duration parameters.
581 *
582 * @return Message $this
583 */
584 public function durationParams( /*...*/ ) {
585 $params = func_get_args();
586 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
587 $params = $params[0];
588 }
589 foreach ( $params as $param ) {
590 $this->parameters[] = self::durationParam( $param );
591 }
592 return $this;
593 }
594
595 /**
596 * Add parameters that are expiration times and will be passed through
597 * Language::formatExpiry before substitution
598 *
599 * @since 1.22
600 *
601 * @param string|string[] $param,... Expiry parameters, or a single argument that is
602 * an array of expiry parameters.
603 *
604 * @return Message $this
605 */
606 public function expiryParams( /*...*/ ) {
607 $params = func_get_args();
608 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
609 $params = $params[0];
610 }
611 foreach ( $params as $param ) {
612 $this->parameters[] = self::expiryParam( $param );
613 }
614 return $this;
615 }
616
617 /**
618 * Add parameters that are time periods and will be passed through
619 * Language::formatTimePeriod before substitution
620 *
621 * @since 1.22
622 *
623 * @param int|int[] $param,... Time period parameters, or a single argument that is
624 * an array of time period parameters.
625 *
626 * @return Message $this
627 */
628 public function timeperiodParams( /*...*/ ) {
629 $params = func_get_args();
630 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
631 $params = $params[0];
632 }
633 foreach ( $params as $param ) {
634 $this->parameters[] = self::timeperiodParam( $param );
635 }
636 return $this;
637 }
638
639 /**
640 * Add parameters that are file sizes and will be passed through
641 * Language::formatSize before substitution
642 *
643 * @since 1.22
644 *
645 * @param int|int[] $param,... Size parameters, or a single argument that is
646 * an array of size parameters.
647 *
648 * @return Message $this
649 */
650 public function sizeParams( /*...*/ ) {
651 $params = func_get_args();
652 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
653 $params = $params[0];
654 }
655 foreach ( $params as $param ) {
656 $this->parameters[] = self::sizeParam( $param );
657 }
658 return $this;
659 }
660
661 /**
662 * Add parameters that are bitrates and will be passed through
663 * Language::formatBitrate before substitution
664 *
665 * @since 1.22
666 *
667 * @param int|int[] $param,... Bit rate parameters, or a single argument that is
668 * an array of bit rate parameters.
669 *
670 * @return Message $this
671 */
672 public function bitrateParams( /*...*/ ) {
673 $params = func_get_args();
674 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
675 $params = $params[0];
676 }
677 foreach ( $params as $param ) {
678 $this->parameters[] = self::bitrateParam( $param );
679 }
680 return $this;
681 }
682
683 /**
684 * Add parameters that are plaintext and will be passed through without
685 * the content being evaluated. Plaintext parameters are not valid as
686 * arguments to parser functions. This differs from self::rawParams in
687 * that the Message class handles escaping to match the output format.
688 *
689 * @since 1.25
690 *
691 * @param string|string[] $param,... plaintext parameters, or a single argument that is
692 * an array of plaintext parameters.
693 *
694 * @return Message $this
695 */
696 public function plaintextParams( /*...*/ ) {
697 $params = func_get_args();
698 if ( isset( $params[0] ) && is_array( $params[0] ) ) {
699 $params = $params[0];
700 }
701 foreach ( $params as $param ) {
702 $this->parameters[] = self::plaintextParam( $param );
703 }
704 return $this;
705 }
706
707 /**
708 * Set the language and the title from a context object
709 *
710 * @since 1.19
711 *
712 * @param IContextSource $context
713 *
714 * @return Message $this
715 */
716 public function setContext( IContextSource $context ) {
717 $this->inLanguage( $context->getLanguage() );
718 $this->title( $context->getTitle() );
719 $this->interface = true;
720
721 return $this;
722 }
723
724 /**
725 * Request the message in any language that is supported.
726 *
727 * As a side effect interface message status is unconditionally
728 * turned off.
729 *
730 * @since 1.17
731 * @param Language|string $lang Language code or Language object.
732 * @return Message $this
733 * @throws MWException
734 */
735 public function inLanguage( $lang ) {
736 $previousLanguage = $this->language;
737
738 if ( $lang instanceof Language ) {
739 $this->language = $lang;
740 } elseif ( is_string( $lang ) ) {
741 if ( !$this->language instanceof Language || $this->language->getCode() != $lang ) {
742 $this->language = Language::factory( $lang );
743 }
744 } elseif ( $lang instanceof StubUserLang ) {
745 $this->language = false;
746 } else {
747 $type = gettype( $lang );
748 throw new MWException( __METHOD__ . " must be "
749 . "passed a String or Language object; $type given"
750 );
751 }
752
753 if ( $this->language !== $previousLanguage ) {
754 // The language has changed. Clear the message cache.
755 $this->message = null;
756 }
757 $this->interface = false;
758 return $this;
759 }
760
761 /**
762 * Request the message in the wiki's content language,
763 * unless it is disabled for this message.
764 *
765 * @since 1.17
766 * @see $wgForceUIMsgAsContentMsg
767 *
768 * @return Message $this
769 */
770 public function inContentLanguage() {
771 global $wgForceUIMsgAsContentMsg;
772 if ( in_array( $this->key, (array)$wgForceUIMsgAsContentMsg ) ) {
773 return $this;
774 }
775
776 $this->inLanguage( MediaWikiServices::getInstance()->getContentLanguage() );
777 return $this;
778 }
779
780 /**
781 * Allows manipulating the interface message flag directly.
782 * Can be used to restore the flag after setting a language.
783 *
784 * @since 1.20
785 *
786 * @param bool $interface
787 *
788 * @return Message $this
789 */
790 public function setInterfaceMessageFlag( $interface ) {
791 $this->interface = (bool)$interface;
792 return $this;
793 }
794
795 /**
796 * Enable or disable database use.
797 *
798 * @since 1.17
799 *
800 * @param bool $useDatabase
801 *
802 * @return Message $this
803 */
804 public function useDatabase( $useDatabase ) {
805 $this->useDatabase = (bool)$useDatabase;
806 $this->message = null;
807 return $this;
808 }
809
810 /**
811 * Set the Title object to use as context when transforming the message
812 *
813 * @since 1.18
814 *
815 * @param Title $title
816 *
817 * @return Message $this
818 */
819 public function title( $title ) {
820 $this->title = $title;
821 return $this;
822 }
823
824 /**
825 * Returns the message as a Content object.
826 *
827 * @return Content
828 */
829 public function content() {
830 if ( !$this->content ) {
831 $this->content = new MessageContent( $this );
832 }
833
834 return $this->content;
835 }
836
837 /**
838 * Returns the message parsed from wikitext to HTML.
839 *
840 * @since 1.17
841 *
842 * @param string|null $format One of the FORMAT_* constants. Null means use whatever was used
843 * the last time (this is for B/C and should be avoided).
844 *
845 * @return string HTML
846 * @suppress SecurityCheck-DoubleEscaped phan false positive
847 */
848 public function toString( $format = null ) {
849 if ( $format === null ) {
850 $ex = new LogicException( __METHOD__ . ' using implicit format: ' . $this->format );
851 \MediaWiki\Logger\LoggerFactory::getInstance( 'message-format' )->warning(
852 $ex->getMessage(), [ 'exception' => $ex, 'format' => $this->format, 'key' => $this->key ] );
853 $format = $this->format;
854 }
855 $string = $this->fetchMessage();
856
857 if ( $string === false ) {
858 // Err on the side of safety, ensure that the output
859 // is always html safe in the event the message key is
860 // missing, since in that case its highly likely the
861 // message key is user-controlled.
862 // '⧼' is used instead of '<' to side-step any
863 // double-escaping issues.
864 // (Keep synchronised with mw.Message#toString in JS.)
865 return '⧼' . htmlspecialchars( $this->key ) . '⧽';
866 }
867
868 # Replace $* with a list of parameters for &uselang=qqx.
869 if ( strpos( $string, '$*' ) !== false ) {
870 $paramlist = '';
871 if ( $this->parameters !== [] ) {
872 $paramlist = ': $' . implode( ', $', range( 1, count( $this->parameters ) ) );
873 }
874 $string = str_replace( '$*', $paramlist, $string );
875 }
876
877 # Replace parameters before text parsing
878 $string = $this->replaceParameters( $string, 'before', $format );
879
880 # Maybe transform using the full parser
881 if ( $format === self::FORMAT_PARSE ) {
882 $string = $this->parseText( $string );
883 $string = Parser::stripOuterParagraph( $string );
884 } elseif ( $format === self::FORMAT_BLOCK_PARSE ) {
885 $string = $this->parseText( $string );
886 } elseif ( $format === self::FORMAT_TEXT ) {
887 $string = $this->transformText( $string );
888 } elseif ( $format === self::FORMAT_ESCAPED ) {
889 $string = $this->transformText( $string );
890 $string = htmlspecialchars( $string, ENT_QUOTES, 'UTF-8', false );
891 }
892
893 # Raw parameter replacement
894 $string = $this->replaceParameters( $string, 'after', $format );
895
896 return $string;
897 }
898
899 /**
900 * Magic method implementation of the above (for PHP >= 5.2.0), so we can do, eg:
901 * $foo = new Message( $key );
902 * $string = "<abbr>$foo</abbr>";
903 *
904 * @since 1.18
905 *
906 * @return string
907 */
908 public function __toString() {
909 // PHP doesn't allow __toString to throw exceptions and will
910 // trigger a fatal error if it does. So, catch any exceptions.
911
912 try {
913 return $this->toString( self::FORMAT_PARSE );
914 } catch ( Exception $ex ) {
915 try {
916 trigger_error( "Exception caught in " . __METHOD__ . " (message " . $this->key . "): "
917 . $ex, E_USER_WARNING );
918 } catch ( Exception $ex ) {
919 // Doh! Cause a fatal error after all?
920 }
921
922 return '⧼' . htmlspecialchars( $this->key ) . '⧽';
923 }
924 }
925
926 /**
927 * Fully parse the text from wikitext to HTML.
928 *
929 * @since 1.17
930 *
931 * @return string Parsed HTML.
932 */
933 public function parse() {
934 $this->format = self::FORMAT_PARSE;
935 return $this->toString( self::FORMAT_PARSE );
936 }
937
938 /**
939 * Returns the message text. {{-transformation is done.
940 *
941 * @since 1.17
942 *
943 * @return string Unescaped message text.
944 */
945 public function text() {
946 $this->format = self::FORMAT_TEXT;
947 return $this->toString( self::FORMAT_TEXT );
948 }
949
950 /**
951 * Returns the message text as-is, only parameters are substituted.
952 *
953 * @since 1.17
954 *
955 * @return string Unescaped untransformed message text.
956 */
957 public function plain() {
958 $this->format = self::FORMAT_PLAIN;
959 return $this->toString( self::FORMAT_PLAIN );
960 }
961
962 /**
963 * Returns the parsed message text which is always surrounded by a block element.
964 *
965 * @since 1.17
966 *
967 * @return string HTML
968 */
969 public function parseAsBlock() {
970 $this->format = self::FORMAT_BLOCK_PARSE;
971 return $this->toString( self::FORMAT_BLOCK_PARSE );
972 }
973
974 /**
975 * Returns the message text. {{-transformation is done and the result
976 * is escaped excluding any raw parameters.
977 *
978 * @since 1.17
979 *
980 * @return string Escaped message text.
981 */
982 public function escaped() {
983 $this->format = self::FORMAT_ESCAPED;
984 return $this->toString( self::FORMAT_ESCAPED );
985 }
986
987 /**
988 * Check whether a message key has been defined currently.
989 *
990 * @since 1.17
991 *
992 * @return bool
993 */
994 public function exists() {
995 return $this->fetchMessage() !== false;
996 }
997
998 /**
999 * Check whether a message does not exist, or is an empty string
1000 *
1001 * @since 1.18
1002 * @todo FIXME: Merge with isDisabled()?
1003 *
1004 * @return bool
1005 */
1006 public function isBlank() {
1007 $message = $this->fetchMessage();
1008 return $message === false || $message === '';
1009 }
1010
1011 /**
1012 * Check whether a message does not exist, is an empty string, or is "-".
1013 *
1014 * @since 1.18
1015 *
1016 * @return bool
1017 */
1018 public function isDisabled() {
1019 $message = $this->fetchMessage();
1020 return $message === false || $message === '' || $message === '-';
1021 }
1022
1023 /**
1024 * @since 1.17
1025 *
1026 * @param mixed $raw
1027 *
1028 * @return array Array with a single "raw" key.
1029 */
1030 public static function rawParam( $raw ) {
1031 return [ 'raw' => $raw ];
1032 }
1033
1034 /**
1035 * @since 1.18
1036 *
1037 * @param mixed $num
1038 *
1039 * @return array Array with a single "num" key.
1040 */
1041 public static function numParam( $num ) {
1042 return [ 'num' => $num ];
1043 }
1044
1045 /**
1046 * @since 1.22
1047 *
1048 * @param int $duration
1049 *
1050 * @return int[] Array with a single "duration" key.
1051 */
1052 public static function durationParam( $duration ) {
1053 return [ 'duration' => $duration ];
1054 }
1055
1056 /**
1057 * @since 1.22
1058 *
1059 * @param string $expiry
1060 *
1061 * @return string[] Array with a single "expiry" key.
1062 */
1063 public static function expiryParam( $expiry ) {
1064 return [ 'expiry' => $expiry ];
1065 }
1066
1067 /**
1068 * @since 1.22
1069 *
1070 * @param int $period
1071 *
1072 * @return int[] Array with a single "period" key.
1073 */
1074 public static function timeperiodParam( $period ) {
1075 return [ 'period' => $period ];
1076 }
1077
1078 /**
1079 * @since 1.22
1080 *
1081 * @param int $size
1082 *
1083 * @return int[] Array with a single "size" key.
1084 */
1085 public static function sizeParam( $size ) {
1086 return [ 'size' => $size ];
1087 }
1088
1089 /**
1090 * @since 1.22
1091 *
1092 * @param int $bitrate
1093 *
1094 * @return int[] Array with a single "bitrate" key.
1095 */
1096 public static function bitrateParam( $bitrate ) {
1097 return [ 'bitrate' => $bitrate ];
1098 }
1099
1100 /**
1101 * @since 1.25
1102 *
1103 * @param string $plaintext
1104 *
1105 * @return string[] Array with a single "plaintext" key.
1106 */
1107 public static function plaintextParam( $plaintext ) {
1108 return [ 'plaintext' => $plaintext ];
1109 }
1110
1111 /**
1112 * @since 1.29
1113 *
1114 * @param array $list
1115 * @param string $type 'comma', 'semicolon', 'pipe', 'text'
1116 * @return array Array with "list" and "type" keys.
1117 */
1118 public static function listParam( array $list, $type = 'text' ) {
1119 if ( !isset( self::$listTypeMap[$type] ) ) {
1120 throw new InvalidArgumentException(
1121 "Invalid type '$type'. Known types are: " . implode( ', ', array_keys( self::$listTypeMap ) )
1122 );
1123 }
1124 return [ 'list' => $list, 'type' => $type ];
1125 }
1126
1127 /**
1128 * Substitutes any parameters into the message text.
1129 *
1130 * @since 1.17
1131 *
1132 * @param string $message The message text.
1133 * @param string $type Either "before" or "after".
1134 * @param string $format One of the FORMAT_* constants.
1135 *
1136 * @return string
1137 */
1138 protected function replaceParameters( $message, $type, $format ) {
1139 // A temporary marker for $1 parameters that is only valid
1140 // in non-attribute contexts. However if the entire message is escaped
1141 // then we don't want to use it because it will be mangled in all contexts
1142 // and its unnessary as ->escaped() messages aren't html.
1143 $marker = $format === self::FORMAT_ESCAPED ? '$' : '$\'"';
1144 $replacementKeys = [];
1145 foreach ( $this->parameters as $n => $param ) {
1146 list( $paramType, $value ) = $this->extractParam( $param, $format );
1147 if ( $type === 'before' ) {
1148 if ( $paramType === 'before' ) {
1149 $replacementKeys['$' . ( $n + 1 )] = $value;
1150 } else /* $paramType === 'after' */ {
1151 // To protect against XSS from replacing parameters
1152 // inside html attributes, we convert $1 to $'"1.
1153 // In the event that one of the parameters ends up
1154 // in an attribute, either the ' or the " will be
1155 // escaped, breaking the replacement and avoiding XSS.
1156 $replacementKeys['$' . ( $n + 1 )] = $marker . ( $n + 1 );
1157 }
1158 } else {
1159 if ( $paramType === 'after' ) {
1160 $replacementKeys[$marker . ( $n + 1 )] = $value;
1161 }
1162 }
1163 }
1164 $message = strtr( $message, $replacementKeys );
1165 return $message;
1166 }
1167
1168 /**
1169 * Extracts the parameter type and preprocessed the value if needed.
1170 *
1171 * @since 1.18
1172 *
1173 * @param mixed $param Parameter as defined in this class.
1174 * @param string $format One of the FORMAT_* constants.
1175 *
1176 * @return array Array with the parameter type (either "before" or "after") and the value.
1177 */
1178 protected function extractParam( $param, $format ) {
1179 if ( is_array( $param ) ) {
1180 if ( isset( $param['raw'] ) ) {
1181 return [ 'after', $param['raw'] ];
1182 } elseif ( isset( $param['num'] ) ) {
1183 // Replace number params always in before step for now.
1184 // No support for combined raw and num params
1185 return [ 'before', $this->getLanguage()->formatNum( $param['num'] ) ];
1186 } elseif ( isset( $param['duration'] ) ) {
1187 return [ 'before', $this->getLanguage()->formatDuration( $param['duration'] ) ];
1188 } elseif ( isset( $param['expiry'] ) ) {
1189 return [ 'before', $this->getLanguage()->formatExpiry( $param['expiry'] ) ];
1190 } elseif ( isset( $param['period'] ) ) {
1191 return [ 'before', $this->getLanguage()->formatTimePeriod( $param['period'] ) ];
1192 } elseif ( isset( $param['size'] ) ) {
1193 return [ 'before', $this->getLanguage()->formatSize( $param['size'] ) ];
1194 } elseif ( isset( $param['bitrate'] ) ) {
1195 return [ 'before', $this->getLanguage()->formatBitrate( $param['bitrate'] ) ];
1196 } elseif ( isset( $param['plaintext'] ) ) {
1197 return [ 'after', $this->formatPlaintext( $param['plaintext'], $format ) ];
1198 } elseif ( isset( $param['list'] ) ) {
1199 return $this->formatListParam( $param['list'], $param['type'], $format );
1200 } else {
1201 if ( !is_scalar( $param ) ) {
1202 $param = serialize( $param );
1203 }
1204 \MediaWiki\Logger\LoggerFactory::getInstance( 'Bug58676' )->warning(
1205 'Invalid parameter for message "{msgkey}": {param}',
1206 [
1207 'exception' => new Exception,
1208 'msgkey' => $this->getKey(),
1209 'param' => htmlspecialchars( $param ),
1210 ]
1211 );
1212
1213 return [ 'before', '[INVALID]' ];
1214 }
1215 } elseif ( $param instanceof Message ) {
1216 // Match language, flags, etc. to the current message.
1217 $msg = clone $param;
1218 if ( $msg->language !== $this->language || $msg->useDatabase !== $this->useDatabase ) {
1219 // Cache depends on these parameters
1220 $msg->message = null;
1221 }
1222 $msg->interface = $this->interface;
1223 $msg->language = $this->language;
1224 $msg->useDatabase = $this->useDatabase;
1225 $msg->title = $this->title;
1226
1227 // DWIM
1228 if ( $format === 'block-parse' ) {
1229 $format = 'parse';
1230 }
1231 $msg->format = $format;
1232
1233 // Message objects should not be before parameters because
1234 // then they'll get double escaped. If the message needs to be
1235 // escaped, it'll happen right here when we call toString().
1236 return [ 'after', $msg->toString( $format ) ];
1237 } else {
1238 return [ 'before', $param ];
1239 }
1240 }
1241
1242 /**
1243 * Wrapper for what ever method we use to parse wikitext.
1244 *
1245 * @since 1.17
1246 *
1247 * @param string $string Wikitext message contents.
1248 *
1249 * @return string Wikitext parsed into HTML.
1250 */
1251 protected function parseText( $string ) {
1252 $out = MessageCache::singleton()->parse(
1253 $string,
1254 $this->title,
1255 /*linestart*/true,
1256 $this->interface,
1257 $this->getLanguage()
1258 );
1259
1260 return $out instanceof ParserOutput
1261 ? $out->getText( [
1262 'enableSectionEditLinks' => false,
1263 // Wrapping messages in an extra <div> is probably not expected. If
1264 // they're outside the content area they probably shouldn't be
1265 // targeted by CSS that's targeting the parser output, and if
1266 // they're inside they already are from the outer div.
1267 'unwrap' => true,
1268 ] )
1269 : $out;
1270 }
1271
1272 /**
1273 * Wrapper for what ever method we use to {{-transform wikitext.
1274 *
1275 * @since 1.17
1276 *
1277 * @param string $string Wikitext message contents.
1278 *
1279 * @return string Wikitext with {{-constructs replaced with their values.
1280 */
1281 protected function transformText( $string ) {
1282 return MessageCache::singleton()->transform(
1283 $string,
1284 $this->interface,
1285 $this->getLanguage(),
1286 $this->title
1287 );
1288 }
1289
1290 /**
1291 * Wrapper for what ever method we use to get message contents.
1292 *
1293 * @since 1.17
1294 *
1295 * @return string
1296 * @throws MWException If message key array is empty.
1297 */
1298 protected function fetchMessage() {
1299 if ( $this->message === null ) {
1300 $cache = MessageCache::singleton();
1301
1302 foreach ( $this->keysToTry as $key ) {
1303 $message = $cache->get( $key, $this->useDatabase, $this->getLanguage() );
1304 if ( $message !== false && $message !== '' ) {
1305 break;
1306 }
1307 }
1308
1309 // NOTE: The constructor makes sure keysToTry isn't empty,
1310 // so we know that $key and $message are initialized.
1311 $this->key = $key;
1312 $this->message = $message;
1313 }
1314 return $this->message;
1315 }
1316
1317 /**
1318 * Formats a message parameter wrapped with 'plaintext'. Ensures that
1319 * the entire string is displayed unchanged when displayed in the output
1320 * format.
1321 *
1322 * @since 1.25
1323 *
1324 * @param string $plaintext String to ensure plaintext output of
1325 * @param string $format One of the FORMAT_* constants.
1326 *
1327 * @return string Input plaintext encoded for output to $format
1328 */
1329 protected function formatPlaintext( $plaintext, $format ) {
1330 switch ( $format ) {
1331 case self::FORMAT_TEXT:
1332 case self::FORMAT_PLAIN:
1333 return $plaintext;
1334
1335 case self::FORMAT_PARSE:
1336 case self::FORMAT_BLOCK_PARSE:
1337 case self::FORMAT_ESCAPED:
1338 default:
1339 return htmlspecialchars( $plaintext, ENT_QUOTES );
1340 }
1341 }
1342
1343 /**
1344 * Formats a list of parameters as a concatenated string.
1345 * @since 1.29
1346 * @param array $params
1347 * @param string $listType
1348 * @param string $format One of the FORMAT_* constants.
1349 * @return array Array with the parameter type (either "before" or "after") and the value.
1350 */
1351 protected function formatListParam( array $params, $listType, $format ) {
1352 if ( !isset( self::$listTypeMap[$listType] ) ) {
1353 $warning = 'Invalid list type for message "' . $this->getKey() . '": '
1354 . htmlspecialchars( $listType )
1355 . ' (params are ' . htmlspecialchars( serialize( $params ) ) . ')';
1356 trigger_error( $warning, E_USER_WARNING );
1357 $e = new Exception;
1358 wfDebugLog( 'Bug58676', $warning . "\n" . $e->getTraceAsString() );
1359 return [ 'before', '[INVALID]' ];
1360 }
1361 $func = self::$listTypeMap[$listType];
1362
1363 // Handle an empty list sensibly
1364 if ( !$params ) {
1365 return [ 'before', $this->getLanguage()->$func( [] ) ];
1366 }
1367
1368 // First, determine what kinds of list items we have
1369 $types = [];
1370 $vars = [];
1371 $list = [];
1372 foreach ( $params as $n => $p ) {
1373 list( $type, $value ) = $this->extractParam( $p, $format );
1374 $types[$type] = true;
1375 $list[] = $value;
1376 $vars[] = '$' . ( $n + 1 );
1377 }
1378
1379 // Easy case: all are 'before' or 'after', so just join the
1380 // values and use the same type.
1381 if ( count( $types ) === 1 ) {
1382 return [ key( $types ), $this->getLanguage()->$func( $list ) ];
1383 }
1384
1385 // Hard case: We need to process each value per its type, then
1386 // return the concatenated values as 'after'. We handle this by turning
1387 // the list into a RawMessage and processing that as a parameter.
1388 $vars = $this->getLanguage()->$func( $vars );
1389 return $this->extractParam( new RawMessage( $vars, $params ), $format );
1390 }
1391 }